﻿using System;
using System.Globalization;
using System.Web.Security.AntiXss;
using System.Web.UI;
using System.Web.UI.WebControls;
using InhollandAir.auxiliary;

namespace InhollandAir
{
    public partial class Checkout : Page
    {
        private static int _userId;
        private static Miles _miles;
        private static int _flightId;
        private static int _bookingId;

        private const int ExchangeRate = 5; // Every 1 IHM saves € 5

        private static int _totalDue;
        private static int _discount;
        private static int _dueAfterDiscount;
        private static DateTime _dueDate = DateTime.Now.AddDays(30);
        private static string _paymentReference;

        private const int DropdownStepSize = 5;



        protected void Page_Load(object sender, EventArgs e)
        {
            CustomerFactory.TryLogin((customer, success) =>
            {
                if (!success || !CheckForBookings()) Response.Redirect("Login.aspx");
                else
                {
                    if (!Page.IsPostBack) LoadMilesDetails();
                    else DiscountCalculator();
                }
            });
        }

        protected void Logout(object sender, EventArgs e)
        {
            CustomerFactory.Logout(true);
        }

        protected bool CheckForBookings()
        {
            if (Session["flight_id"] != null && Session["amount_persons"] != null && Session["booking_id"] != null)
            if (!string.IsNullOrEmpty(Session["flight_id"].ToString()) && !string.IsNullOrEmpty(Session["amount_persons"].ToString()) && !string.IsNullOrEmpty(Session["booking_id"].ToString()))
                try
                {
                    _flightId = Convert.ToInt16(Session["flight_id"]);
                    _bookingId = Convert.ToInt16(Session["booking_id"]);
                    _totalDue = Sql.GetPriceForFlight(_flightId) * Convert.ToInt16(Session["amount_persons"]);
                    var status = Sql.GetBookingStatusById(Convert.ToInt16(Session["booking_id"]));
                    _userId = status[0];
                    if (status[1] == 1)
                        return true;
                }
                catch (Exception)
                {
                    return false;
                }
            return false;
        }

        protected void LoadMilesDetails()
        {
            //Get balance
            _miles = new Miles().GetMiles(_userId);
            string balance = _miles.Balance.ToString(CultureInfo.InvariantCulture);

            //Set labels with balance and exchange rate
            lblCurrentBalance.Text = AntiXssEncoder.HtmlEncode(balance, false);
            lblExchangeRate.Text = AntiXssEncoder.HtmlEncode(ExchangeRate.ToString(CultureInfo.InvariantCulture), false);
            lblMoneySaved.Text = AntiXssEncoder.HtmlEncode("Make a selection first...", false);

            //Add discount options per 5, up to their balance or total due
            ddlMilesSelection.Items.Add(new ListItem("None", "0"));
            if (int.Parse(balance) >= DropdownStepSize)
                for (int i = DropdownStepSize; i < int.Parse(balance) && i < (_totalDue / ExchangeRate); i += DropdownStepSize)
                    ddlMilesSelection.Items.Add(new ListItem(i + " IHM", i.ToString(CultureInfo.InvariantCulture)));
        }

        protected void DiscountCalculator()
        {
            //Calculate discount in currency (not miles)
            _discount = int.Parse(ddlMilesSelection.SelectedValue)*ExchangeRate;
            lblMoneySaved.Text = AntiXssEncoder.HtmlEncode(string.Format("{0:C}", _discount), false);

            //Calculate total due after discount
            _dueAfterDiscount = _totalDue - _discount;
            lblTotalDue.Text = AntiXssEncoder.HtmlEncode(string.Format("{0:C}", _dueAfterDiscount), false);

            //Show due date
            lblDueDate.Text = AntiXssEncoder.HtmlEncode(_dueDate.ToString("dd/MM/yyyy"), false);
        }

        protected void BtnFinishCheckoutClick(object sender, EventArgs e)
        {
            //Check all values again as this is the most important part of the process
            bool maxMiles = int.Parse(ddlMilesSelection.SelectedValue) <= (_miles.Balance/ExchangeRate);
            bool minDue = _dueAfterDiscount >= (DropdownStepSize*ExchangeRate) && _dueAfterDiscount > 0;
            bool maxDiscount = _discount < _totalDue;

            if (maxDiscount && maxMiles && minDue)
                //Update booking status to finalized (2)
                if (Sql.UpdateBookingStatus(_bookingId, 2) == "1" && Sql.UpdateMilesAmount(_userId, int.Parse(ddlMilesSelection.SelectedValue), false) == "1")
                {
                    //Use crypto random to generate the payment reference
                    _paymentReference = CryptoRandom.GetPaymentReference();
                    lblPaymentReference.Text = AntiXssEncoder.HtmlEncode(_paymentReference, false);
                    btnFinishCheckout.Visible = false;
                }
                else
                    lblPaymentReference.Text = AntiXssEncoder.HtmlEncode("Booking is still in process or already paid for!", false);
            else
                lblPaymentReference.Text = AntiXssEncoder.HtmlEncode("Illegal action found - no reference created.", false);
        }
    }
}